<?php
/** [类型表逻辑层模型]
 * @Author: 976123967@qq.com
 * @Date:   2015-01-15 11:01:36
 * @Last Modified by:   chenli
 * @Last Modified time: 2015-02-28 22:57:28
 */
class TypeLogic extends Model{
	// 指定表名
	protected $tableName = 'type';
	private $cache;

	public function _initialize()
	{
		$this->cache  = S('type');
	}

	/**
	 * [get_all 读取所有类型]
	 * @return [type] [description]
	 */
	public function get_all()
	{
		return $this->cache;
	}

	/**
	 * [update_cache 更新缓存]
	 * @return [type] [description]
	 */
	public function update_cache()
	{
		$data = $this->order(array('typeid'=>'asc'))->select();
		$temp = array();
		if($data)
		{
			foreach($data as $k=>$v)
			{
				$temp[$v['typeid']] = $v;
			}
		}
	
		// 写缓存
		S('type',$temp);
	}

	/**
	 * [add_type 添加类型]
	 */
	public function add_type()
	{
		if(!$this->create())
			return false;
		$typeid = $this->add();

		// 更新缓存
		$this->update_cache();
		return $typeid;
	}

	/**
	 * [find_one 查找一条记录]
	 * @return [type] [description]
	 */
	public function find_one()
	{
		$typeid = I('get.typeid');

		if(!$this->cache)
		{
			$this->error = '类型不存在';
			return false;
		}

		foreach($this->cache as $k=>$v)
		{
			if($k==$typeid)
			{
				return $v;
			}
		}
		$this->error = '类型不存在';
		return false;
	}

	/**
	 * [update_field 更新]
	 * @return [type] [description]
	 */
	public function update_field()
	{
		if(!$this->create())
			return false;
		$this->save();
		// 更新缓存
		$this->update_cache();
		return true;
	}

	/**
	 * [del_type description]
	 * @return [type] [description]
	 */
	public function del_type()
	{
		$typeid = I('get.typeid');
		// 验证类型是否存在
		if(!isset($this->cache[$typeid]))
		{
			$this->error = '类型不存在';
			return false;
		}

		// 验证类型下面是否还有属性
		$attr = D('Attr','Logic')->get_all_by_typeid($typeid);
		if($attr)
		{
			$this->error = '请先删除属性';
			return false;
		}

		// 删除
		$this->delete($typeid);
		// 更新缓存
		$this->update_cache();
		return true;
	}	
}